package com.wang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.entity.UserContract;
import com.wang.entity.UserImage;
import com.wang.entity.UserInfo;
import com.wang.mapper.UserContractMapper;
import com.wang.mapper.UserImageMapper;
import com.wang.service.UserInfoService;
import com.wang.mapper.UserInfoMapper;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import jakarta.annotation.security.RolesAllowed;
import kotlin.jvm.internal.Lambda;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author 25312
* @description 针对表【t_user_info(用户信息表)】的数据库操作Service实现
* @createDate 2025-04-23 10:13:53
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService {
     @Autowired
     private UserInfoMapper userInfoMapper;

     @Autowired
     private UserImageMapper userImageMapper;

     @Autowired
     private UserContractMapper userContractMapper;

     @Autowired
     private MinioClient minioClient;

    @Override
    public UserInfo getUserById(Integer id) {
        return userInfoMapper.selectUserById(id);
    }


    @Override
    public boolean deleteUserById(Integer id)throws Exception{
        //查询合同表、头像表中的button,object
        UserInfo userInfo = userInfoMapper.selectUserById(id);

        //删除合同表信息
        LambdaQueryWrapper<UserContract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(UserContract::getUid,id);
        userContractMapper.delete(contractWrapper);

        //删除头像表信息
        LambdaQueryWrapper<UserImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(UserImage::getUid,id);
        userImageMapper.delete(imageWrapper);

        //删除用户表信息
        int delUser = userInfoMapper.deleteById(id);

        //删除minio中对应的头像和合同 需要判断一下合同和头像是否存在
        if(null != userInfo.getUserContractDO()){
            //1.删除合同
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(userInfo.getUserContractDO().getBucket())
                    .object(userInfo.getUserContractDO().getObject())
                    .build());
        }
        if(null != userInfo.getUserImageDO()){
            //2.删除头像
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(userInfo.getUserImageDO().getBucket())
                    .object(userInfo.getUserImageDO().getObject())
                    .build());

        }

        //这里不用判断合同表和头像表是否删除成功，因为这两个表中可以没有对应的数据
        return delUser > 0 ? true : false;
    }
}




